<?php

class LoginController {

    public function invoke() {
        if (!isset($_SESSION['username'])) {
            $dir = dirname(__FILE__);
            $xtpl = new XTemplate($dir . DS . "view" . DS . "view.php");
            $p = '';
            $u = '';
            if (isset($_POST['u']) && isset($_POST['p'])) {
                $u = $_POST['u'];
                $p = $_POST['p'];
                $user=$this->login($u, $p);
                if ($user!=null) {
                    $_SESSION['username'] = $u;
                    $_SESSION['userid']=$user->getTK_ID();
                    $_SESSION['avatar']=$user->getTK_AVATAR();
                    $_SESSION['nvid']=$user->getNV_ID();
                    header("location: index.php?com=com_home");
                } else {
                    echo "<script>alert('Tài khoản không tồn tại')</script>";
                    echo '<meta http-equiv="refresh" content="0;index.php?com=com_login">';
                }
            } else {
                $xtpl->parse('main');
                $xtpl->out('main');
            }
        } else {
            header("location: index.php?com=com_home");
        }
    }

    private function login($u, $p) {
        require_once LIBRARIES_ENTITIES_DATABASE;
        $db = new Database();
        try {
            $login = new M_Tai_khoan();
            $login->setTK_USERNAME($u);
            $login->setTK_PASSWORD($p);
            $login = $login->login($db);
            return $login;
        } catch (Exception $exc) {
            echo $exc->getTraceAsString();
        }
    }
    private function logout(){
        session_destroy();
    }

}
